<?php

	include_once('getDBConnection.php');
	include_once('FavoriteFood.php');

	$obj = new DBConnection();
	$mysqli = $obj->getDBC();



	if(isset($_POST['fields']) && !empty($_POST['fields'])){//This is the name of the variable that holds all the food history
		$myArray = $_POST['fields'];
		$deleteQuery = "delete from " . Constants::FOOD_HISTORY . " where " . Constants::FOOD_DATE . " = '$myArray[3]';";


		$mysqli->query($deleteQuery);



		if($mysqli->error){
				die('An error occurred while remove old food history for the date of ' . $myArray[3] . '. Error = ' . $mysqli->error);
		}


		$saveQuery = "insert into " . Constants::FOOD_HISTORY . " ( ".
			Constants::FOOD_HISTORY_ID . ", " .
			Constants::PROFILE_ID . ", " .
			Constants::QUICK_ID . ", " .
			Constants::FOOD_DATE . ", " .//not numeric
			Constants::MEAL_TIME . ", " .//not numeric
			Constants::MEAL_SERVING_SIZE . ") values ";
		for($i=0, $size=sizeof($myArray);$i<$size;$i++){
			if($i % Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY == 0){
				$saveQuery .= "($myArray[$i] ";
			}else if($i % Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY != Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY-1){//if not last row
				if($i % Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY == Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY-2 ||
					$i % Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY == Constants::NUM_OF_COLUMNS_IN_FOOD_HISTORY-3){

					$saveQuery .= ", '$myArray[$i]'";//done to format non numeric values
				}else{
					$saveQuery .= ", $myArray[$i]";
				}
			}else{//assume this is last row for each set of the number of columns in the table
				$saveQuery .= ", $myArray[$i])";
				if($i + 1 < $size){//check to see if another row will be added
					$saveQuery .= ", ";
				}
			}
		}
		$saveQuery .= ";";
		$result = $mysqli->query($saveQuery);

		if($mysqli->error){
			die('An error occurred save food history for the date of ' . $myArray[3] . '. Error = ' . $mysqli->error);
		}

		print($result);

	}else{
		print_r('Failure');
	}






?>